package com.zsjt.app.service.impl;

import com.zsjt.app.mapper.AccountMapper;
import com.zsjt.app.pojo.PermissionDto;
import com.zsjt.app.pojo.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private AccountMapper accountMapper;

    public UserDetailsServiceImpl() {
    }

    @Autowired
    @Qualifier("accountMapper")
    public void setAccountMapper(AccountMapper accountMapper) {
        this.accountMapper = accountMapper;
    }

    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
       // System.out.println("username:" + account);
        UserDto user = this.accountMapper.findUserDtoByUserAccount(account);
        if (user == null) {
            return null;
        } else {
       //    System.out.println("用户名：" + user.getAccount() + ",密码：" + user.getPassword());
            List<PermissionDto> permissionDtos = this.accountMapper.findUserPermissionByUserId(user.getId());
            List<String> permissions = new ArrayList();
            permissionDtos.forEach((c) -> {
                permissions.add(c.getCode());
            });
            String[] permissionsArray = new String[permissions.size()];
            permissions.toArray(permissionsArray);
            UserDetails userDetails = User.withUsername(user.getAccount()).password(user.getPassword()).authorities(permissionsArray).build();
            return userDetails;
        }
    }
}
